/*
 * @Descripttion: axios 封装入口文件
 * @version:
 * @Author: HYH
 * @Date: 2022-07-19 11:32:38
 * @LastEditors: HYH
 * @LastEditTime: 2022-08-19 10:12:33
 */

import axios, { AxiosRequestConfig, Method } from 'axios' //这个是官方方法
import { ElLoading } from 'element-plus'
import ElMessage from '@/utils/resetMessage'
import { nextTick } from 'vue'
const baseURL = import.meta.env.VITE_APP_URL
/**axios实例 */
const instance = axios.create({
  baseURL, //接口统一域名
  timeout: 50000, //设置请求超时时间
  headers: {
    'Content-Type': 'application/json;charset=UTF-8;'
  }
})

let loadingInstance: any
/**loading开启 */
const startLoading = () => {
  loadingInstance = ElLoading.service({
    lock: true,
    // text: '请求中...',
    background: 'rgba(0, 0, 0, 0.5)'
  })
  // loadingInstance = ElLoading.service({
  //   spinner: 'box1 my-loading ',
  //   background: 'rgba(0, 0, 0, 0.5)'
  // })
}
/**loading关闭 */
const endLoading = () => {
  nextTick(() => {
    loadingInstance.close()
  })
}
// 添加请求拦截器
instance.interceptors.request.use(
  request => {
    startLoading()
    return request
  },
  error => {
    endLoading()
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  response => {
    endLoading()
    // 解码之后返回解码后的数据
    return response
  },
  error => {
    endLoading()
    ElMessage.error(error.message)
    // ElMessage.error('服务器错误')
    return Promise.reject(error.message)
  }
)

export default instance
